package com.gyg.deadLockDemo;

/**
 * 死锁案例：线程1和2竞争资源
 */
public class deadlock {
    public static void main(String[] args) {
        ExecuteFactory threadA = new ExecuteFactory(new ResourceA(), "线程A");
        ExecuteFactory threadB = new ExecuteFactory(new ResourceB(), "线程B");
        new Thread(threadA).start();
        new Thread(threadB).start();
        //System.out.println(ExecuteFactory.resource1==ExecuteFactory.resource1);
    }
}

/**
 * 资源1
 */
class ResourceA {

}

/**
 * 资源2
 */
class ResourceB {

}

class ExecuteFactory implements Runnable {

    //使用static修饰的原因是，在JVM加载时，static修饰的资源只会有一份
    static ResourceA resourceA = new ResourceA();
    static ResourceB resourceB = new ResourceB();

    //线程持有的资源
    Object resource;
    //线程名
    String threadName;

    ExecuteFactory(Object resource, String threadName) {
        this.resource = resource;
        this.threadName = threadName;
    }

    @Override
    public void run() {
        try {
            executeMethod();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行方法
     */
    public void executeMethod() throws InterruptedException {
        if (resource instanceof ResourceA) {
            //如果持有资源1，给资源1加锁，并且获取资源2的锁
            synchronized (resourceA) {
                System.out.println(threadName + "获取到资源A...");
                Thread.sleep(1000);
                synchronized (resourceB) {
                    System.out.println(threadName + "获取到资源B...");
                    Thread.sleep(1000);
                    System.out.println(threadName + "执行完毕...");
                }
            }
        } else {
            //获取资源后释放资源
            synchronized (resourceB) {
                System.out.println(threadName + "获取到资源B...");
                Thread.sleep(2000);
                //获取资源B后再获取资源A，发生死锁
                synchronized (resourceA) {
                    System.out.println(threadName + "获取到资源A...");
                    Thread.sleep(1000);
                }
            }

        }
    }
}


